<template>
  <div>
    <a-form-model ref="LoginFormRef" :model="Loginform" :rules="rules">
      <a-form-model-item prop="userNameOrEmailAddress">
        <a-input
          ref="userNameInput"
          v-model="Loginform.userNameOrEmailAddress"
          placeholder="登录名"
          allow-clear
        >
          <a-icon slot="prefix" type="user" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item prop="password">
        <a-input-password placeholder="密码" v-model="Loginform.password">
          <a-icon slot="prefix" type="lock" />
        </a-input-password>
      </a-form-model-item>
      <a-form-model-item>
        <div class="LoginBtn_wrap">
          <a-button type="primary" :loading="loginBtnStart" size="large" @click="Login">登录</a-button>
        </div>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
const checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("只可输入字母、数字"));
    }
  }
  callback();
};
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      loginBtnStart: false, //开启按钮的loading状态
      //表单数据
      Loginform: {
        userNameOrEmailAddress: "axb",
        password: "123456"
      },
      //表单验证规则
      rules: {
        userNameOrEmailAddress: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          },
          {
            validator: checkData,
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            min: 6,
            message: "密码长度不能小于6位",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    ...mapMutations(["setAccessToken"]),
    ...mapMutations("StudentLogin", ["setStudentInfo"]),
    ...mapMutations("Signalr", ["StartConnection"]),

    Login() {
      if (
        this.$refs.LoginFormRef.validate(val => {
          if (val) {
            this.$api.StudentLogin(this.Loginform).then(({ data }) => {
              this.setAccessToken(data.result.accessToken);
              this.setStudentInfo(data.result.user);
              this.$router.push("/studenthome");

              //链接Signalr
              this.StartConnection();
            });
          }
        })
      );
    }
  }
};
</script>

<style lang="less" scoped>
.ant-form {
  margin: 3% 5% !important;
  .ant-input {
    height: 45px;
  }
}

.LoginBtn_wrap {
  display: flex;
  justify-content: center;
}
</style>